
//  ComposeViewController.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/26.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit
import SVProgressHUD

let emotionKeyboardViewH: CGFloat = 216

class ComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        self.textView.becomeFirstResponder()
    }
    
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "didClickReturnButton")
        
        navigationItem.titleView = titleView
        
        //添加发送按钮
        //注意: 要禁用导航条上右边 Item 内部的按钮的话,需要使用如下命令,直接 rightButton.enable = false 是没用的
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        
        //添加控件
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(composePicView)
        
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.view)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.bottom.trailing.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        composePicView.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(view).offset(10)
            make.width.equalTo(view).offset(-20)
            make.top.equalTo(100)
            make.height.equalTo(SCREENW - 20)
        }
        
//        emotionView.snp_makeConstraints { (make) -> Void in
//            
//            make.width.equalTo(SCREENW)
//            make.height.equalTo(216)
//        }
        
        //深坑
        //        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardDidChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didClickBackDeleteButton", name: ClickDeleteButtonNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didClickEmoticonBtn:", name: ClickEmotionButtonNotification, object: nil)
    }
    
    // MARK: - 移除通知
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 点击表情按钮收到通知后的方法
    @objc private func didClickEmoticonBtn(noti:NSNotification){
        
        let emotion = noti.userInfo!["emotion"] as! EmotionModel
//        print("通知~\(emotion.chs)")
        
        //判断 type
        if emotion.type! == "1"{
            
            //说明是emoji表情
            textView.insertText((emotion.code! as NSString).emoji())
            
        }else{
            
            print("图片表情")
            
            textView.insertEmotion(emotion)
            //以下代码抽取到分类中去了
//            //图片表情上屏(图文混排) ~~ NSAttributedString
//            //1.将现有文字的 attributedText 生成一个 NSMutableAttributedString
//            let originAttr = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            //2.通过表情模型生成表情图片 -> 通过图片生成 NSTextAttachment -> 通过 attachment 生成一个 NSAttributedString
//            //            let image = UIImage(named: "\(emotion.folderName)/\(emotion.png)", inBundle: EmotionKeyboardViewModel.sharViewModel.loadBundle(), compatibleWithTraitCollection: nil)
//            let image = UIImage(named: "\(emotion.folderName ?? "")/\(emotion.png ?? "")", inBundle: EmotionKeyboardViewModel.sharViewModel.loadBundle(), compatibleWithTraitCollection: nil)
//            let attachment = NSTextAttachment()
//            attachment.image = image
//            //设置图片的大小
//            let attachmentHW = textView.font!.lineHeight
//            attachment.bounds = CGRect(x: 0, y: -4, width: attachmentHW, height: attachmentHW)
//            let newAttr = NSAttributedString(attachment: attachment)
//            
//            //3. 将第2部生成的 NSAttributedString 添加到第1步生成的 NSMutableAttributedString 里面
//            //获取光标的位置
//            var selectedRange = textView.selectedRange
////            originAttr.appendAttributedString(newAttr)
////            originAttr.insertAttributedString(newAttr, atIndex: selectedRange.location)
//            originAttr.replaceCharactersInRange(selectedRange, withAttributedString: newAttr)
//            // 设置字体大小
//            originAttr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, originAttr.length))
//            
//            //4. 将第3步的执行结果赋值给 textView.attributedText
//            textView.attributedText = originAttr
//            
//            //防止输入完成后光标又跳回去
//            selectedRange.location += 1
//            selectedRange.length = 0
//            textView.selectedRange = selectedRange
        }
    }
    
    // MARK: - 点击删除按钮收到通知后的方法
    @objc private func didClickBackDeleteButton(){
        
        // UITextView 自带的回退删除的 API
        textView.deleteBackward()
    }
    
    // MARK: - 收到键盘通知后的方法
    @objc private func keyboardFrameChange(noti:NSNotification){
        
        //        print(noti)
        /*
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        UIKeyboardIsLocalUserInfoKey = 1;
        */
        //       print(noti.userInfo)
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //        print(endFrame)
        
        composeToolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(endFrame.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    // MARK: - 点击返回按钮
    @objc private func didClickReturnButton(){
        
        self.textView.resignFirstResponder()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 点击选择图片按钮
    private func selectedPic(){
        
        //        print("selectedPic")
        
        let pickerVc = UIImagePickerController()
        
        // 判断 camera 是否可用
        //UIImagePickerController.isCameraDeviceAvailable(.Front)
        // 判断某个数据方式是否可用
        // UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType)
        // 如何去拍照？
        // vc.sourceType = .Camera
        // 裁剪图片
        // vc.allowsEditing = true
        
        //设置代理
        pickerVc.delegate = self
        
        presentViewController(pickerVc, animated: true, completion: nil)
    }
    
    // MARK: - 懒加载照片视图ComposePicView
    private lazy var composePicView: ComposePicView = {
        
        let picView = ComposePicView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        //设置要执行的闭包
        picView.composeImgClosure = {
            
            self.selectedPic()
        }
        
        return picView
    }()
    
    //懒加载ComposeToolBar
    private lazy var composeToolBar: ComposeToolBar = {
        
        let toolBar = ComposeToolBar(frame: CGRectZero)
        
        //设置要执行的闭包
        toolBar.buttonClickClosure = {[weak self] (type) in
            
            //            print(type)
            
            switch type {
            case .Picture:
                self?.selectedPic()
                break
            case .Mention:
                break
            case .Trend:
                break
            case .Keyboard:
                self?.switchKeyboard()
                break
            case .Add:
                break
            }
        }
        return toolBar
    }()
    
    // MARK: - 切换键盘
    private func switchKeyboard(){
        
        print("switchKeyboard")
//        if textView.inputView == nil {
//
//            //系统键盘 --> 需要切换成表情键盘
//            textView.inputView = emotionView
//        }else{
//            
//            //表情键盘 --> 需要切换成系统键盘
//            textView.inputView = nil
//        }
    
        textView.inputView = (textView.inputView == nil) ? emotionView : nil
        
        composeToolBar.isSystemKeyboard = (textView.inputView == nil)
        
        //当自定义键盘 和 系统键盘进行切换时, 需要进行刷新
        // If called while object is first responder, reloads inputView, inputAccessoryView, and textInputMode.  Otherwise ignored.
        textView.reloadInputViews()
    }

    // MARK: - 懒加载控件
    private lazy var emotionView:EmotionKeyboardView = {
        
        let emotion =  EmotionKeyboardView(frame: CGRectZero)
        
        emotion.frame.size = CGSizeMake(SCREENW, emotionKeyboardViewH)
        
        return emotion
    }()
    
    // MARK: - 懒加载textView
    private lazy var textView: UITextView = {
        
        let textView = TextView()
        
        textView.placeholder = "听说下雨天音乐和巧克力更配哟~~~"
        //        textView.text = "mlmlmmml"
        
        textView.font = UIFont.systemFontOfSize(18)
        
        //设置代理,监听文字变化
        textView.delegate = self
        
        // UITextView
        //拖动时隐藏键盘(系统会弹出警告),需要2个属性一起设置
        textView.keyboardDismissMode = .OnDrag
        //开启垂直方向的弹簧效果
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    
    private lazy var rightButton: UIButton = {
        
        let rightButton = UIButton(titleColor: UIColor.whiteColor(), titleFont: 15, imageName: "common_button_orange")
        
        rightButton.setTitle("发送", forState: UIControlState.Normal)
        
        //添加点击事件
        rightButton.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside)
        
        //        rightButton.setBackgroundImage(self.scalePic("common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        //        rightButton.setBackgroundImage(self.scalePic("common_button_white_disable"), forState: UIControlState.Disabled)
        
        rightButton.setBackgroundImage(UIImage.scalePic("common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        rightButton.setBackgroundImage(UIImage.scalePic("common_button_white_disable"), forState: UIControlState.Disabled)
        
        //设置不同状态下文字的颜色
        rightButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        
        rightButton.frame.size = CGSizeMake(50, 30)
        //        rightButton.sizeToFit()
        
        return rightButton
    }()
    
    // MARK: - 发微博的方法
    @objc private func send(){
        
        
//        var result = ""
//        let attr = textView.attributedText
//        
//        //遍历富文本里的内容
//        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) -> Void in
////            print(attr.string)
////            print(dict)
////            print("=========")
////            print(range)
//            if let attribute = dict["NSAttachment"] as? XHTextAttachment{
//                //取到的是表情字符串
////                print("表情字符串\(attribute.emoticon?.chs)")
//                result += attribute.emoticon?.chs ?? ""
//            }else{
//                //取到的是文字
//                print(attr.string)
//                result += (attr.string as NSString).substringWithRange(range)
//            }
//        }
//        print(result)
        if composePicView.hidden {
            
            //发送文字微博
            updateText()
        }else{
            
            //发送图片微博
            uploadPic()
        }
        
        textView.text = nil
//        textView.resignFirstResponder()
        composePicView.hidden = true
        composePicView.images.removeAll()
    }
    
    // MARK: - 发送图片微博的方法
    func uploadPic(){
        
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let parameters = [
            "access_token":UserAccountViewModel.sharedViewModel.account?.access_token ?? "",
            "status":textView.emotionText!]
        
        //抽取到了NetworkTools
//        NetworkTools.sharedTools.POST(url, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
//            let data = UIImagePNGRepresentation(self.composePicView.images.first!)!
//            //拼接二进制文件
//            /**
//            - 1. 要上传的二进制数据
//            - 2. 该二进制数组对应的接口里面的名字
//            - 3. 传到后台之后的文字名字。一般都乱写，因为后台基本不会使用你写的名字
//            - 4. mimeType: 告诉后台我们传上去的二进行数据具体是什么类型的
//            - image/jpeg
//            - 大类型/小类型
//            - 如果不想让后台知道：application/octet-stream
//            */
//            formData.appendPartWithFileData(data, name: "pic", fileName: "bbaj", mimeType: "application/octet-stream")
//            }, progress: nil, success: { (_, responseObject) -> Void in
//                SVProgressHUD.showSuccessWithStatus("发送成功")
//            }) { (_, error) -> Void in
//                print(error)
//                SVProgressHUD.showErrorWithStatus("发送失败")
//        }
        
        let data = UIImagePNGRepresentation(self.composePicView.images.first!)!
        let datas = ["pic":data]
        NetworkTools.sharedTools.postPicture(url, datas: datas, parameters: parameters) { (responseObject, error) -> Void in
            
            if error != nil{
                
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
        
        
    }
    
    // MARK: - 发送文字微博的方法
    func updateText(){
        
        let url = "https://api.weibo.com/2/statuses/update.json"
        
        let parameters = [
            "access_token":UserAccountViewModel.sharedViewModel.account?.access_token ?? "" ,
            "status":textView.emotionText!]
        NetworkTools.sharedTools.request(RequestMethod.POST, urlString: url, parameters: parameters) { (responseObject, error) -> Void in
            
            if error != nil{
                
                print("错误\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
            
        }
        
    }
    
    
    // MARK: - 拉伸图片的方法
    //    private func scalePic(imageStr: String) -> UIImage{
    //
    //        var image = (UIImage(named: imageStr))!
    //        image = image.resizableImageWithCapInsets(UIEdgeInsets(top: image.size.height / 2, left: image.size.width / 2, bottom: image.size.height / 2, right: image.size.width / 2))
    //        return image
    //    }
    
    // MARK: - 发微博标题文字设置
    private lazy var titleView:UILabel = {
        
        let titleView = UILabel()
        
        if let name = (UserAccountViewModel.sharedViewModel.account?.name){
            
            titleView.textAlignment = .Center
            
            let text = "发微博\n\(name)"
            
            titleView.text = text
            
            titleView.font = UIFont.systemFontOfSize(14)
            //指定行数
            titleView.numberOfLines = 0
            
            //求出 name 所在的字符串范围
            let range = (text as NSString).rangeOfString(name)
            
            //添加副文本的属性
            let attrText = NSMutableAttributedString(string: text)
            attrText.addAttributes([NSForegroundColorAttributeName : UIColor.redColor(),NSFontAttributeName: UIFont.systemFontOfSize(12),NSStrokeWidthAttributeName: 2,NSStrokeColorAttributeName: UIColor.redColor()], range: range)
            
            //设置 Label 的副文本
            titleView.attributedText = attrText
            
        }else{
            
            titleView.text = "发微博"
        }
        titleView.sizeToFit()
        return titleView
    }()
    
    
    
}

// MARK: - UITextView 的代理方法
extension ComposeViewController:UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
}

// MARK: - UIPickerController 的代理方法
extension ComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    // The picker does not dismiss itself; the client dismisses it in these callbacks.
    //实现代理方法后系统不会自动 dismiss UIPickerController,需要用户手动销毁
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let img = image.scaleToWidth(600)
        
                composePicView.addImage(img)
        
        //测试
//        let data = UIImagePNGRepresentation(img)
//        data?.writeToFile("/Users/Tiffanybbaj/Desktop/\(random()/10).png", atomically: true)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

